<template>
  <el-table
    :data="rows"
    v-on="$listeners"
  >
    <el-table-column
      v-if="selector !== false"
      header-align="center"
      type="selection"
      align="center"
      width="55px"
      v-bind="selector"
    />
    <template v-for="col in columns">
      <el-table-column
        header-align="center"
        align="center"
        v-bind="col"
        :label="col.label"
        :key="col._index"
        :prop="col.name"
        :width="col._width + 'px'"
      >
        <template slot-scope="scope">
          <ed-editable-table-cell
            v-if="col.edit"
            :col="col"
            :value="scope.row[col.name]"
            @edit="edit(col, scope.row, $event)"
          >
            <ed-table-cell
              :col="col"
              :value="scope.row[col.name]"
            />
          </ed-editable-table-cell>
          <ed-table-cell
            v-else
            :col="col"
            :value="scope.row[col.name]"
          />
        </template>
      </el-table-column>
    </template>
    <el-table-column
      v-if="actions"
      header-align="center"
      align="center"
      :width="actionsWidth"
      label="操作"
    >
      <template slot-scope="scope">
        <ed-toolbar
          :row="scope.row"
          v-bind="actions"
          @click="click"
          size="mini"
        />
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import EdToolbar from './EdToolbar'
import EdTableCell from './table/EdTableCell.vue'
import EdEditableTableCell from './table/EdEditableTableCell.vue'

export default {
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    selector: {
      type: [Object, Boolean],
      default: () => ({})
    },
    rows: {
      type: Array,
      default: () => []
    },
    actions: {
      type: Object,
      default: () => ({})
    },
    /**
     * 多选数组
     */
    selected: {
      type: Array,
      default: () => []
    }
  },
  components: {
    EdToolbar,
    EdTableCell,
    EdEditableTableCell
  },
  watch: {
    /**
     * 响应多选置入
     */
    selected (s, old) {
      if (s === old) return
      // 没有选择行
      if (!s) this.$refs.table.clearSelection()
      this.rows.forEach((row) => {
        if (row.id && (s.findIndex(id => +id === +row.id) !== -1)) {
          this.$refs.table.toggleRowSelection(row)
        }
      })
    }
  },
  computed: {
    /**
     * 计算行按钮列宽
     */
    actionsWidth () {
      if (!this.actions.items) return '0'
      return `${this.actions.items.length * 90}px`
    }
  },
  methods: {
    /**
     * 响应行按钮
     */
    click (btn, row) {
      this.$emit('click', btn, row)
    },
    edit (col, row, v) {
      this.click({
        ...col.edit,
        cell: true
      }, {
        id: row.id,
        name: col.name,
        value: v
      })
    }
  }
}

</script>

<style scoped>

</style>
